import axios from 'axios'

const instance = axios.create({
	withCredentials: false, //携带cookie
	timeout: 10000,
	headers: {
		get: {
			'Content-Type': 'application/x-www=form-urlencoded'
		},
		post: {
			'Content-Type': 'application/x-www=form-urlencoded'
		}
	},
});

//请求之前做判断
instance.interceptors.request.use(config => {
	// 判断token
	if (sessionStorage.getItem("token")) {
		config.headers.Authorization = sessionStorage.getItem("token");
	} else {
		transformRequest: [function(data, headers) {
			//这个请求不需要请求头(在此处删除，上方设置的请求头。)
			if (headers.common.Authorization) {
				delete headers.common.Authorization;
			}
			return data;
		}]
	}
	return config;
}, error => {
	console.error("参数错误", 'fail');
	return Promise.reject(error);
});

//响应时做判断
instance.interceptors.response.use(
	response => {
		if (response.data.message == '请先登录') {
			return response;
		} else if (response.data.status === 400) {
			router.push('/login')
			return response;
		} else {
			return response;
		}
	},
	error => {
		return Promise.reject(error)
	});

export default instance;
